package com.zmn.uac.business.impl.user;

import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.saas.common.enums.NumberEnum;
import com.zmn.uac.business.interfaces.user.UserInfoBService;
import com.zmn.uac.client.TokenClient;
import com.zmn.uac.client.UserListClient;
import com.zmn.uac.client.VasOrderListClient;
import com.zmn.uac.common.dro.oauth.login.UserAuthLoginDRO;
import com.zmn.uac.common.exception.TokenOutTimeException;
import com.zmn.uuc.common.constant.PassConsts;
import com.zmn.uuc.common.dro.pass.PassIdentityBaseDRO;
import com.zmn.uuc.common.dro.user.UserDetailDRO;
import com.zmn.vas.common.dro.CheckDRO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类描述：用户信息业务实现
 *
 * @author xujie
 * @since 2021/06/15 17:17
 */
@Slf4j
@Service
public class UserInfoBServiceImpl implements UserInfoBService {

    private static final String TAG = "用户信息业务实现";

    @Resource
    TokenClient tokenClient;

    @Resource
    UserListClient userListClient;

    @Resource
    VasOrderListClient vasOrderListClient;

    @Override
    public ResponseDTO<Long> getUserIdByToken(String token) {
        List<PassIdentityBaseDRO> passIdentityBaseList = tokenClient.listPassIdentityByToken(token);

        List<PassIdentityBaseDRO> passIdentityBase = passIdentityBaseList.stream().filter(p
                -> p.getIdentityType() == PassConsts.PASS_IDENTITY_TYPE_PERSON &&
                GlobalConsts.YES == Optional.ofNullable(p.getLogined()).orElseGet(NumberEnum.ONE::getKey))
                .collect(Collectors.toList());
        if (CollectionUtil.isNullOrEmpty(passIdentityBase)) {
            return ResponseDTO.fail("获取登录用户失败！");
        }
        if (passIdentityBase.size() > 1) {
            return ResponseDTO.fail("获取登录用户失败,存在多条同时登陆信息！");
        }
        PassIdentityBaseDRO passIdentity = passIdentityBase.get(0);
        return ResponseDTO.success(passIdentity.getIdentityObjectId());
    }

    @Override
    public ResponseDTO<Long> getPassIdByToken(String token) {
        List<PassIdentityBaseDRO> passIdentityBaseList = tokenClient.listPassIdentityByToken(token);

        List<PassIdentityBaseDRO> passIdentityBase = passIdentityBaseList.stream().filter(p
                -> p.getIdentityType() == PassConsts.PASS_IDENTITY_TYPE_PERSON &&
                GlobalConsts.YES == Optional.ofNullable(p.getLogined()).orElseGet(NumberEnum.ONE::getKey))
                .collect(Collectors.toList());
        if (CollectionUtil.isNullOrEmpty(passIdentityBase)) {
            return ResponseDTO.fail("获取登录用户失败！");
        }
        if (passIdentityBase.size() > 1) {
            return ResponseDTO.fail("获取登录用户失败,存在多条同时登陆信息！");
        }
        PassIdentityBaseDRO passIdentity = passIdentityBase.get(0);
        return ResponseDTO.success(passIdentity.getPassId());
    }

    @Override
    public ResponseDTO<UserAuthLoginDRO> getUserInfoByToken(String token) {

        ResponseDTO<Long> response = getUserIdByToken(token);
        if (!response.isSuccess()) {
            return ResponseDTO.fail(response.getMessage());
        }
        Long userId = response.getData();
        return getUserInfoByTokenAndUserId(token, userId, null);
    }

    @Override
    public ResponseDTO<UserAuthLoginDRO> getUserInfoByTokenAndUserId(String token, Long userId, String openId) {
        if (StringUtil.isBlank(token)) {
            return ResponseDTO.fail("token不能为空");
        }
        UserAuthLoginDRO userAuth = new UserAuthLoginDRO();
        if (Objects.nonNull(userId)) {
            UserDetailDRO userDetail = userListClient.getThirdUserDetailByIdAndOpenId(userId, Boolean.FALSE, openId);

            String substring = String.valueOf(userId).substring(userId.toString().length() - 6, userId.toString().length());
            String userName = StringUtil.isNotBlank(userDetail.getUserName()) ? userDetail.getUserName() : "用户" + substring;
            String realName = StringUtil.isNotBlank(userDetail.getNickName()) ? userDetail.getNickName() : userName;
            if (substring.equals(realName.trim())) {
                realName = "用户" + realName;
            }
            userAuth.setUserName(userName);
            userAuth.setRealName(realName);
            userAuth.setMobile(userDetail.getMobile());

            userAuth.setAvatarSrc(userDetail.getAvatarSrc());
            userAuth.setUserId(userId);
        }
        userAuth.setToken(token);
        checkBuildUserIsMember(token, userAuth);
        return ResponseDTO.success(userAuth);
    }


    /**
     * 判断并组装用户会员信息
     *
     * @param token    token
     * @param userAuth userAuth
     * @author xujie
     * @since 2021/05/19
     */
    private void checkBuildUserIsMember(String token, UserAuthLoginDRO userAuth) {

        List<PassIdentityBaseDRO> passIdentityBaseDROList = tokenClient.listPassIdentityByToken(token);
        if (CollectionUtils.isEmpty(passIdentityBaseDROList)) {
            log.error("[{}], 授权登陆获取登陆用户信息通行证信息不存在或者过期了,请重新登录请求参数token:{}", TAG, token);
            throw new TokenOutTimeException("重新登录!");
        }
        // 个人用户
        List<PassIdentityBaseDRO> passIdentityBaseList = passIdentityBaseDROList.stream().filter(passIdentity -> passIdentity.getIdentityType() == PassConsts.PASS_IDENTITY_TYPE_PERSON).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(passIdentityBaseList)) {
            log.warn("[{}], 获取通行证不存在个人用户信息:{}", TAG, token);
            return;
        }
        List<Long> userIdList = passIdentityBaseList.stream().map(PassIdentityBaseDRO::getIdentityObjectId).collect(Collectors.toList());
        List<CheckDRO> checkList = vasOrderListClient.checkNineDollarsNineByUserIds(userIdList);
        if (CollectionUtil.isNotNullOrEmpty(checkList)) {
            checkList = checkList.stream().filter(check -> Objects.nonNull(check.getExpireTime())).sorted(Comparator.comparing(CheckDRO::getExpireTime).reversed()).collect(Collectors.toList());
            CheckDRO check = checkList.stream().filter(it -> Objects.equals(GlobalConsts.YES, it.getResult())).findFirst().orElse(null);
            if (Objects.nonNull(check)) {
                userAuth.setMemberStatusBool(Boolean.TRUE);
                userAuth.setMemberExpireTime(DateUtil.dateFormatToString(check.getExpireTime(), DateUtil.FORMAT_DEFAULT));
                userAuth.setMemberOrderId(check.getOrderId());
            }
        }
        log.warn("[{}], 获取用户9.9会员信息失败,此处记录日志不影响流程!", TAG);
    }
}
